﻿using Se.Common;
using Se.Log;
using Se.Model.Data;
using Se.Model.Template.Common;
using SeServer.Module.Character;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SeServer.Module
{
    /// <summary>
    /// 游戏模块集合
    /// </summary>
    public class GameControllerManager
    {
        public GameControllerManager()
        { }

        /// <summary>
        /// 模块集合
        /// </summary>
        private Dictionary<ControllerType, ModuleControllerBase> _moduleSet = new Dictionary<ControllerType, ModuleControllerBase>();

        public ModuleControllerBase this[ControllerType type]
        {
            get
            {
                ModuleControllerBase controller;
                this._moduleSet.TryGetValue(type, out controller);

                return controller;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Initilize()
        {
            this.LoadModules();
            this.LoadTemplates();
            this.LoadModuleMemoryData();
        }

        /// <summary>
        /// 加载模块
        /// </summary>
        private void LoadModules()
        {
            var assemblies = Utility.GetCurrentAssemblies();
            foreach (var assembly in assemblies)
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.BaseType != typeof(ModuleControllerBase))
                        continue;

                    ModuleControllerBase module = (ModuleControllerBase)Activator.CreateInstance(type);
                    this._moduleSet[module.ControllerType] = module;
                    SeLog.Info("Initializing the Business Module: {0}", module.ControllerType.ToString());
                    module.InitModule();
                }
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadTemplates()
        {
            GameTemplateManager.Current.Init(SqlType.SQLServer, System.Configuration.ConfigurationManager.AppSettings["Con"], ReaderType.CSV, System.Configuration.ConfigurationManager.AppSettings["TemplatePath"]);
            foreach (var controllerItem in this._moduleSet)
            {
                controllerItem.Value.LoadTemplates();
            }
        }

        /// <summary>
        /// 加载常驻内存数据
        /// </summary>
        private void LoadModuleMemoryData()
        {
            foreach (var controllerItem in this._moduleSet)
            {
                controllerItem.Value.LoadMemoryData();
            }
        }

    }
}
